package com.dragon.pear.common.spring.security;

import com.dragon.common.base.exceptions.CommonException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

public class CustomBearerTokenAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException {
//        ServerHttpResponse response = exchange.getResponse();
        String token = request.getHeader("Authorization");
        System.out.println("Authorization: " + token);

        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON.toString());

        String errorMessage = "Token验证失败";

        // 安全地处理异常类型
        if (ex instanceof OAuth2AuthenticationException) {
            OAuth2Error error = ((OAuth2AuthenticationException) ex).getError();
            //errorMessage = error.getDescription();
            errorMessage = "未通过认证";

            if (ex instanceof InvalidBearerTokenException) {
                ex.printStackTrace();
                errorMessage = "BearerToken格式错误";
            }

            // 特殊处理过期错误
            if (error.getDescription().contains("expired")) {
                errorMessage = "您的登录已过期，请重新登录";
            }

        } else if (ex.getCause() instanceof OAuth2AuthenticationException) {
            OAuth2Error error = ((OAuth2AuthenticationException) ex.getCause()).getError();
            errorMessage = "未通过认证";
        }

//        String body = HttpResult.fail(401, errorMessage).toJson();
//        System.out.println("body: " + body);
//
//        response.getWriter().write(body.getBytes(StandardCharsets.UTF_8));

        throw CommonException.of(401, errorMessage);
    }
}